package com.zhu.androidsample.business.girls.presenter;

import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;

import com.android.volley.Response;
import com.zhu.androidsample.business.girls.GirlActivity;
import com.zhu.androidsample.business.girls.bean.GirlBean;
import com.zhu.androidsample.common.BaseActivity;
import com.zhu.androidsample.common.BasePresenter;
import com.zhu.androidsample.common.UrlMap;
import com.zhu.androidsample.util.JsonBeanUtil;
import com.zhu.androidsample.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ZCP on 2015/11/19.
 * mail:43426073@qq.com
 */
public class GirlPresenter extends BasePresenter implements AdapterView.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {

    public static final int COUNT = 9;

    int page = 0;//翻页——页码
    Response.Listener<String> girlListener = new BasePresenter.Listener() {
        @Override
        public void onResponse(String s) {
            super.onResponse(s);
            ArrayList<Object> list = null;
            try {
                JSONObject object = new JSONObject(s);
                list = new ArrayList<>(COUNT);

                for (int i = 0; i < COUNT; i++) {
                    JSONObject jb = object.optJSONObject(i + "");
                    list.add(JsonBeanUtil.json2Bean(jb, GirlBean.class));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.d(TAG, "onResponse() page: " + page);
            if (page == 0) {
                updateActivity(GirlActivity.SET_DATA, list);
            } else {
                updateActivity(GirlActivity.APPEND_DATA, list);
            }
        }
    };
    String key = "";//关键词

    public GirlPresenter(BaseActivity activity) {
        super(activity);
    }


    public void initData() {
        loadDate(true);
    }


    public void loadMore() {
        loadDate(false);
    }

    public void goDetail() {
        // TODO: 2015/11/26
    }


    private void loadDate(boolean isReflash) {
        if (isReflash) {
            page = 0;
        } else {
            page = page + 1;
        }
        Map<String, String> params = new HashMap<>();//新建一个参数容器
        params.put("num", (COUNT + 1) + "");//添加一个num参数，个数
        params.put("page", (page + 1) + "");//添加页码
        params.put("rand", 1 + "");//添加页码
        getRequest(UrlMap.GIRL_PHOTO, params, girlListener);//开始请求数据
    }

    @Override
    public void onRefresh() {
        initData();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ToastUtil.show(position + "-----" + id);
    }


}
